<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;
use App\Models\Users;
use App\Models\Linkslists;
use App\Models\Memberorders;
use App\Models\Miniappsorder;
use App\Models\Userslogs;
use App\Models\Usersrecharges;
use App\Models\Usersinvitations;
use App\Models\Usersincomes;
use App\Models\Usersauthority;
use App\Models\Minappimage;
use App\Models\Task;
use App\Models\Worklink;
use App\Services\WechatService;
use App\Services\CommonService;
use App\Services\WechattmplmsgService;
use App\Services\CalltaskService;
use App\Services\OutputService;
use App\Jobs\Miniappswitch;
use App\Jobs\Htmlosshanndle;
use App\Jobs\Wxkfhanndle;
use Log,Pay,Exception,DB;

class IndexController extends Controller
{
    // 小程序登录
    public function miniappLogin(Request $request)
    {
        if (empty($request->code)) return response()->json(["status"=>"error","code"=>"2001","msg"=>"非法请求,请稍后重试！"]);
        if ($request->platefrom == 1) {
            return response()->json(["status"=>"error","code"=>"1001","msg"=>"这是外链跳转专用的小程序,不支持登录;请前往【天天外链】小程序登录！"]);
            $codeinfo = WechatService::code2Session($request->code,"wx9e47aa0184e15958","b3c287d21d3625cf1877caa1ef5517ee");
            if (!isset($codeinfo["openid"])) return response()->json(["status"=>"error","code"=>"2001","msg"=>"登录异常,请稍后重试！"]);
        } else if ($request->platefrom == 4) {
            return response()->json(["status"=>"error","code"=>"1001","msg"=>"这是外链跳转专用的小程序,不支持登录;请前往【天天外链】小程序登录！"]);
            $codeinfo = WechatService::code2Session($request->code,"wx2ab2135aba908413","eeeb631bf4742a9df02e59618ddd5148");
            if (!isset($codeinfo["openid"])) return response()->json(["status"=>"error","code"=>"2001","msg"=>"登录异常,请稍后重试！"]);
        } else if ($request->platefrom == 3) {
            return response()->json(["status"=>"error","code"=>"1001","msg"=>"这是外链跳转专用的小程序,不支持登录;请前往【天天外链】小程序登录！"]);
            $codeinfo = WechatService::code2Session($request->code,"wxe442f596f1e31c70","c8cc6af872b57d3ddb6701961fd649ab");
            if (!isset($codeinfo["openid"])) return response()->json(["status"=>"error","code"=>"2001","msg"=>"登录异常,请稍后重试！"]);
        } else if ($request->platefrom == 10) {
            $codeinfo = WechatService::code2Session($request->code,"wx820e151d0905ab1a","60e60ad4e4cd75996aec80b104e41964");
            if (!isset($codeinfo["openid"])) return response()->json(["status"=>"error","code"=>"2001","msg"=>"登录异常,请联系客服！"]);
        } else {
            $codeinfo = WechatService::code2Session($request->code,"wx671547aa7fc09f10","9a7b6b49923ea399915c1a9600bdee8a");
            if (!isset($codeinfo["openid"])) return response()->json(["status"=>"error","code"=>"2001","msg"=>"登录异常,请联系客服！"]);
        }
        $openid = $codeinfo["openid"];
        $unionid = isset($codeinfo["unionid"]) ? $codeinfo["unionid"] : "";
        $users = Users::getUsersByOpenid($openid);
        // 判断是否有其他注册
        if (empty($users) && !empty($unionid)) $users = Users::getUsersByUnionid($unionid);
        if (empty($users)) {
            $users_id = Users::creatUsersByOpenid($openid,$request->avatar,$request->nike,$request->gender,$request->address,$unionid,3);
            Usersauthority::createUsersAuthority($users_id,1,1);
            // 获取邀请人,增加邀请记录
            if (!empty($request->users_invitation_id) && $request->users_invitation_id != "undefined") {
                Usersinvitations::addUsersInvitation($users_id,$request->users_invitation_id);
            }
            $users = Users::getUsersByOpenid($openid);
        } else {
            // 账号已被禁用
            if ($users->disable == 2) return response()->json(["status"=>"error","code"=>"2001","msg"=>"对不起，此账号已被禁用！"]);
            Users::miniapBindWebOpenid($users->id,$openid,$request->avatar,$request->nike,$request->gender,$request->address,$unionid);
            $users_id = $users->id;
        }
        $users_id   = encrypt($users_id);
        $data = $users->toArray();
        // unset($data['id']);
        $data['users_id'] = $users_id;
        return response()->json(["status"=>"success","code"=>"1000","msg"=>"登录成功！","users"=>$data]);
    }

    public function appLogin(Request $request)
    {
        if (empty($request->openid)) return response()->json(["status"=>"error","code"=>"2001","msg"=>"非法请求,请稍后重试！"]);

        $openid = $request->openid;
        $users = Users::getUsersByOpenid($openid);
        if (empty($users)) {
            $users_id = Users::creatUsersByOpenid($openid,$request->avatar,$request->nike,$request->gender,$request->address);
            Usersauthority::createUsersAuthority($users_id,1,1);
            $users = Users::getUsersByOpenid($openid);
            // 获取邀请人,增加邀请记录
            if (!empty($request->users_invitation_id)) {
                Usersinvitations::addUsersInvitation($users->id,$request->users_invitation_id);
            }
        } else {
            Users::updateUsersByOpenid($openid,$request->avatar,$request->nike,$request->gender,$request->address);
        }
        $member = Memberorders::getLastLinksOrders($users->id);
        Usersauthority::createUsersAuthority($users->id,1,1);
        $users_id   = encrypt($users->id);
        $data = $users->toArray();
        unset($data['id']);
        $data['users_id'] = $users_id;
        $data['links_member'] = empty($member->product_id) ? "" : $member->product_id;
        $data['links_member_time'] = empty($member->end_time) ? "" : $member->end_time;
        return response()->json(["status"=>"success","code"=>"1000","msg"=>"登录成功！","users"=>$data]);
    }

    public function products(Request $request)
    {
        $platfrom = empty($request->platfrom) ? "online" : $request->platfrom;
        if ($platfrom == "online") {
            $products = Memberorders::$products;
        } elseif ($platfrom == "agent") {
            $products = Memberorders::$agentproducts;
        } else {
            $products = Memberorders::$devproducts;
        }
        $months = [["id"=>"1","name"=>"1个月","value"=>"1","discount"=>"10"],["id"=>"2","name"=>"3个月","value"=>"3","discount"=>"8.5"],["id"=>"4","name"=>"1年","value"=>"12","discount"=>"5.5"]];
        return response()->json(["status"=>"success","code"=>"1000","msg"=>"获取信息成功！","data"=>$products,"months"=>$months]);
    }

    public function wechatMember(Request $request)
    {
        $product_id = $request->product_id;
        $users_id = $request->users_id;
        $out_trade_no = md5(time().rand("10000","99999"));
        $month = is_numeric($request->month) ? $request->month : 1;

        $products = Memberorders::$products;
        $product = collect($products)->where("id",$product_id)->first();

        if ($product["price"] <= 0) return response()->json(["status"=>"error","code"=>"1001","msg"=>"免费会员无需购买！","data"=>[]]);

        // 获取最新会员
        $orders = Memberorders::ordersDetial($users_id);
        if ($request->type == 1) {
            // 购买会员
            if ($month == 12) {
                $price = $product["price"]*$month*0.55;
            } elseif ($month == 3) {
                $price = $product["price"]*$month*0.85;
            } else {
                $price = $product["price"]*$month;
            }
            $member_time = strtotime("+".$month." months");
            $title = $product["title"]."-新购";
        } elseif ($request->type == 2) {
            // 原来的套餐
            $productold = collect($products)->where("id",$orders->product_id)->first();
            // 结束时间
            $member_time = $orders->end_time <= time() ? time() : $orders->end_time;
            // 相差多少天
            $days = floor(($member_time-time())/86400);
            $price = round((($product["price"]-$productold["price"])/30)*$days,2);
            $title = $product["title"]."-升级";
        } else {
            // 续费会员
            if ($month == 12) {
                $price = $product["price"]*$month*0.55;
            } elseif ($month == 3) {
                $price = $product["price"]*$month*0.85;
            } else {
                $price = $product["price"]*$month;
            }
            if (isset($orders->end_time)) {
                $lasttime = $orders->end_time <= time() ? date("Y-m-d H:i:s",time()) : date("Y-m-d H:i:s",$orders->end_time);
            } else {
                $lasttime = date("Y-m-d H:i:s",time());
            }
            $member_time = strtotime("$lasttime +".$month." months");
            $title = $product["title"]."-续费";
        }
        // 添加新的订单
        Memberorders::addOrders($users_id,$out_trade_no,$title,time(),$member_time,$product_id,$price,1);
        $user  = Users::getUsersById($users_id);
        if ($request->platefrom == "App") {
            $order  = [
                'out_trade_no' => $out_trade_no,
                'total_amount' => $price,
                'subject'      => $product["title"],
                'passback_params'=>'member',
            ];
            $result = Pay::alipay(config('pay.alipay'))->app($order)->getContent();
        } else {
            $order = [
                'out_trade_no' => $out_trade_no,
                'total_fee' => round($price*100,0),
                'body' => $product["title"],
                'attach' => 'member',
                'openid' => $user->openid,
            ];
            try {
                $result = Pay::wechat(config('pay.wechat'))->miniapp($order);
            } catch (Exception $e) {
                return response()->json(["status"=>"error","code"=>"1001","msg"=>"发起支付失败,请前往后台支付或联系客服。"]);
            }
        }
        return response()->json(["status"=>"success","code"=>"1000","msg"=>"订单提交成功","data"=>["member_time"=>$member_time,"wechat"=>$result]]);
    }

    // 调起微信充值
    public function wechatRecharge(Request $request)
    {
        $user   = Users::getUsersById($request->users_id);
        $left_money = $user->money + $request->amount;
        $out_trade_no = md5(time().rand("10000","99999"));

        Usersrecharges::usersRechargesInsert($request->users_id, $out_trade_no, $request->amount,2);
        $recharge = $request->amount*100;
        $order = [
            'out_trade_no' => $out_trade_no,
            'total_fee' => $recharge,
            'body' => '费用充值('.$request->amount.'元)',
            'attach' => 'recharge'
        ];
        if ($request->platefrom == "App") {
            $result = Pay::wechat(config('pay.wechat'))->app($order)->getContent();
        } else {
            $order['openid'] = $user->openid;
            $result = Pay::wechat(config('pay.wechat'))->miniapp($order);
        }
        return response()->json(["status"=>"success","code"=>"1000","msg"=>"订单提交成功","data"=>$result]);
    }


    public function wechatBack(Request $request)
    {
        $res = $request->getContent();
        $pay = Pay::wechat(config('pay.wechat'));
        $data = $pay->verify(); // 是的，验签就这么简单！
        if ($data->return_code != 'SUCCESS') return '支付失败';
        // 该状态为会员充值
        // if ($data->attach == "member") {
            $order = Memberorders::getByOrderNo($data->out_trade_no);
            if (empty($order)) return '订单不存在';
            if ($order->pay_status != 2) return $pay->success();
            $total_fee = $data->total_fee/100;
            if ($order->price != $total_fee) return $pay->success();

            // 修改订单状态
            Memberorders::updatePayStatus($data->out_trade_no, [
                'pay_status'    => 3,
                'transaction_id' => $data->transaction_id,
                'type'          => 1,
            ]);

            if ($order->product_id == 2) {
                $limit_pv = 50000;
                $limit_status = 1;
            } elseif ($order->product_id == 3) {
                $limit_pv = 500000;
                $limit_status = 1;
            } elseif ($order->product_id == 4) {
                $limit_pv = 1000000;
                $limit_status = 2;
            } else {
                $limit_pv = 100;
                $limit_status = 1;
            }
            // 把全部订单改为可用
            Linkslists::updateLinksListsStatus($order->users_id,$limit_status,$limit_pv,$order->end_time);
            Worklink::updateWorkLinkMember($order->users_id,$limit_pv,$order->end_time);
            Userslogs::addUsersLogs($order->users_id, "会员充值成功！","您的会员充值成功,充值方式: 微信 会员到期时间:".date("Y-m-d",$order->end_time),$order->id);

            $itations = Usersinvitations::getUsersInvitation($order->users_id);
            // 判断是否有邀请人
            if (!empty($itations)) {
                $batch = date("Ym",time());
                $incomes = Usersincomes::getbatchIncomes($itations->users_invitation_id,$batch);
                if (empty($incomes)) {
                    $commission = $order->price*0.1;
                    Usersincomes::addbatchIncomes($itations->users_invitation_id,$batch,$order->price,$commission);
                } else {
                    if ($incomes->money <= 1000) {
                        $commission = $order->price*0.1;
                    } elseif ($incomes->money <= 5000) {
                        $commission = $order->price*0.2;
                    } elseif ($incomes->money <= 10000) {
                        $commission = $order->price*0.3;
                    }
                    $money = $order->price+$incomes->money;
                    $commission = $commission+$incomes->commission;
                    Usersincomes::updatebatchIncomes($incomes->id,$money,$commission);
                }
            }
            Users::updateUsersMemberTime($order->users_id,$order->product_id,$order->end_time);
            // 会员开通公众号推送
            $users = Users::getUsersWechatOpenid($order->users_id);
            WechattmplmsgService::sendMemberTempleteMsg($users->wechat_openid,$users->username,$order->product_id,date("Y-m-d H:i:s",$order->start_time),date("Y-m-d H:i:s",$order->end_time));
            // 更新线上OSS
            Htmlosshanndle::dispatch($order->users_id,"","")->delay(10);
            Wxkfhanndle::dispatch($order->users_id)->delay(10);
        // } else {
        //     // 查询充值记录
        //     $order = Usersrecharges::usersRechargesById($data->out_trade_no);
        //     $total_fee = $data->total_fee/100;
        //     if ($order->money != $total_fee) return $pay->success();
        //     if ($order->status != 1) return $alipay->success();
        //     $orderinfo = [
        //         'out_biz_no' => $data->transaction_id,
        //         'status'     => 2,
        //         'openid'   => $data->openid,
        //     ];
        //     // 更新支付状态
        //     Usersrecharges::usersRechargesUpdateByOrderId($data->out_trade_no, $orderinfo);
        //     // 更新余额
        //     Users::incrementUsersMoney($order->users_id, $total_fee);
        // }
        return $pay->success();
    }

    public function scanPay(Request $request)
    {        
        $pay = Pay::wechat(config('pay.wechat'));
        $data = $pay->verify(); // 是的，验签就这么简单！
        if ($data->return_code != 'SUCCESS') return '支付失败';
        // 该状态为会员充值
        $out_trade_no = $data->out_trade_no;
        // 该状态为会员充值
        $order = Miniappsorder::miniappOrderDetial($data->out_trade_no);
        if (empty($order)) return '订单不存在';
        if ($order->pay_status != 1) return $pay->success();
        $total_fee = $data->total_fee/100;
        if ($order->price != $total_fee) return $pay->success();

        // 修改订单状态
        Miniappsorder::updatePayStatus($data->out_trade_no, [
            'pay_status' => 3,
            'transaction_id' => $data->transaction_id
        ]);
        return $pay->success();
    }

    public function wechatPayBack(Request $request)
    {
        $res = $request->getContent();
        $pay = Pay::wechat(config('pay.wechat'));
        $data = $pay->verify(); // 是的，验签就这么简单！
        if ($data->return_code != 'SUCCESS') return '支付失败';
        // 该状态为会员充值
        $order = Miniappsorder::orderPayStatus($data->out_trade_no);
        if (empty($order)) return '订单不存在';
        if ($order->pay_status != 1) return $pay->success();
        $total_fee = $data->total_fee/100;
        if ($order->price != $total_fee) return $pay->success();
        // 修改订单状态
        Miniappsorder::updatePayStatus($data->out_trade_no, [
            'pay_status' => 3,
            'transaction_id' => $data->transaction_id
        ]);
        return $pay->success();
    }
}
